package com.zzptc.myappNaozho;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    private TextView alarmText;
    private Button setBtn,cancelBtn;
    private AlarmManager alarmManager;
    private PendingIntent pi;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //设置监听
        setListener();




    }

    private void setListener() {
        setBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTime();

            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alarmManager.cancel(pi);
                alarmText.setText("闹钟设置：当前没有设置闹钟");

            }
        });
    }

    private void setTime() {
        TimePickerDialog td=new TimePickerDialog(MainActivity.this,
                1, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
                String h=hourOfDay<10 ? "0"+hourOfDay:""+hourOfDay;
                String m=minute<10 ? "0"+minute:""+minute;

                Calendar c=Calendar.getInstance();
                c.set(Calendar.HOUR_OF_DAY,hourOfDay);
                c.set(Calendar.MINUTE,minute);
                c.set(Calendar.SECOND,0);

                setpi();
                alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pi);
                alarmText.setText("起床闹钟设置为："+h+":"+m);

                //alarmText.setText("起床闹钟设置为："+hourOfDay+":"+minute);

            }
        },0,0,true);
        td.show();

    }

    private void setpi() {
        Intent i=new Intent("com.zzptc.myapp0914.2.ClockReceiver");
        ClockReceiver cr=new ClockReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.zzptc.myapp0914.ClockReceiver");
        registerReceiver(cr,filter);


    }

    private void initView() {
        alarmText=findViewById(R.id.alarmText);
        setBtn=findViewById(R.id.setBtn);
        cancelBtn=findViewById(R.id.cancelBtn);


    }
}